﻿using System;
using System.Web.Mvc;
using Operations;

namespace ValidationAction.Mvc
{
    public class ValidationActionResult:ActionResult
    {
        private Func<object, ActionResult> _success;
        private Func<object, ActionResult> _error;

        public ValidationActionResult Success(Func<object, ActionResult> success)
        {
            _success = success;
            return this;
        }

        public ValidationActionResult Error(Func<object, ActionResult> error)
        {
            _error = error;
            return this;
        }

        private readonly Func<IOperation> _action;

        public ValidationActionResult(Func<IOperation> action)
        {
            _action = action;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            string validationError;

            var actionDispatcher = new OperationProcessor();
            actionDispatcher.SetAction(_action);

            if (!actionDispatcher.CanExecute(out validationError))
            {
                if(_error != null)
                    _error(validationError).ExecuteResult(context);
                
                return;
            }

            if(_success != null)
                _success(actionDispatcher.Execute<object>()).ExecuteResult(context);
         }
    }
}